<?php

namespace app\model;

use app\service\HomeService;
use app\traits\ModelTrait;
use Exception;
use support\Cache;
use support\Redis;
use think\Model;

class UserToken extends Model
{
    use ModelTrait;

    /**
     * @param User $user
     * @return array
     * @throws Exception
     */
    public static function createToken(User $user): array
    {
        $tokenInfo = $user->getToken();
        $data      = [
            'uid'          => $user->id,
            'token'        => $tokenInfo['token'],
            'type'         => $tokenInfo['type'] ?? WEB_WWW,
            'expires_time' => date('Y-m-d H:i:s', $tokenInfo['params']['exp']),
            'create_time'  => time(),
            'date_v'       => date('Y-m-d'),
            'os_type'      => request()->os_type,
        ];
        (new self())->replace(true)->save($data);
        return $data;
    }

    /**
     * @param User $user
     * @param int  $loginType
     * @return array
     * @throws Exception
     */
    public static function loginToken(User $user, int $loginType = 0): array
    {
        $_token = UserToken::createToken($user);
        $token  = $_token['token'] ?? '';

        $session_id = request()->session()->getId();
        if (request()->os_type == 3) Cache::set(UID_SESSION_KEY . '_' . $session_id, $token, 3600 * 24); // 缓存N天 cache为file存储时不能选用此方法
        $token_type = HomeService::instance()->get_second_host();
        if ($_token) {
            $login_data['uid']               = $user['id'];
            $login_data['last_login_time']   = myDate();
            $login_data['last_login_date_v'] = date('Y-m-d');
            $login_data['ip']                = request()->getRealIp();
            $login_data['login_type']        = $loginType;
            $login_data['token']             = $token;
            $login_data['token_type']        = $token_type;
            $login_data['os_type']           = request()->os_type;
            (new UserLoginLog)->replace(true)->save($login_data);
            $data = [
                [
                    'id'     => $user['id'],
                    'mobile' => $user['mobile'],
                    'status' => $user['status'],
                    'avatar' => $user['avatar'],
                ],
                $user['id']
            ];
            Redis::set(APP_TOKEN_LOGIN . $token, json_encode($data), 'EX', 60 * 60 * 24 * 1, 1);
        }
        return $_token;
    }
}